"""
===============================================
* filename: scan_tool.py
* author:   zhangbing
* describe: 源码扫描工具,判断有没有调用或使用深度学习框架和知识图谱

* modifier:
* time:
* content:
===============================================
"""
import os
import argparse
# function: 扫描文件夹下符合条件的文件名
# 参数:
#         directory：需要扫描的文件夹
#         prefix:    前缀
#         postfix：  后缀
# return:   符合条件的文件的文件名组成的list

def get_filenames(directory, prefix=None, postfix=None):
    files_list = []
    # 扫描文件夹的.py文件
    for (root, dirs, files) in os.walk(directory):

        for special_file in files:
            if special_file.endswith(postfix):
                files_list.append(os.path.join(root, special_file))
                for sub_dir in dirs:
                    files_list.extend(get_filenames(sub_dir, prefix, postfix))

    return files_list

# function:判断一个文件夹中的是否含有某些关键字
# 参数:
#         directory：需要扫描的文件夹
#         prefix:前缀
#         postfix：后缀
# return:
#         True:文件夹中存在含有关键字的文件
#         False:文件夹中不存在含有关键字的文件
def directory_match(project_dir,keywords=['tensorflow', 'neo4j','torch.nn'],prefix='', postfix='.py'):

    ret = {}
    ret['Values'] = False
    ret['ValueInfos'] = ""
    ret['Err'] = 0
    ret['ErrInfo'] = ''

    if os.path.exists(project_dir) == False:
        ret['Err'] = -1
        ret['ErrInfo'] = 'there is no such directory'
        return ret

    list = get_filenames(project_dir, prefix=prefix, postfix=postfix)
    for file_name in list:
        with open(file_name, 'r', encoding='utf-8') as f:
            contents = f.read()
            for key_word in keywords:
                if (contents.find(key_word) > -1):
                    ret['ValueInfos'] = "find key word \'" + key_word + '\' in file: ' + file_name
                    ret['Values'] = True
                    return ret
    ret['ValueInfos'] = "can't find any key word \'"
    ret['Values'] = False
    return ret

if __name__ == "__main__":
    # keywords = ['tensorflow', 'neo4j']
    # directory_match(project_dir="F:\\share_to_linux\\CapsNet-Tensorflow",keywords=keywords,postfix='.py')
    # directory_match(project_dir="F:\\share_to_linux\\Deep_RL_Implementations", keywords=keywords, postfix='.py')

    #解析输入参数
    parser = argparse.ArgumentParser(description='scan_tool')
    parser.add_argument('directory', type=str, help="position")     #必填参数

    parser.add_argument('--keywords', type=str,nargs="+", default=['tensorflow', 'neo4j','torch.nn'])
    parser.add_argument('--prefix', type=str, default=None)
    parser.add_argument('--postfix', type=str, default='.py')
    args = parser.parse_args()
    # print(args)
    if len(args.directory) <= 0:
        print('Please input the director!')
        exit(-1)
    if directory_match(project_dir=args.directory, keywords=args.keywords,prefix=args.prefix, postfix=args.postfix):
        print('It\'s a Deep Learning or Knowledge Graph project')
    else:
        print('It\'s not a Deep Learning or Knowledge Graph project')

# 使用方法：
# python scan_tool.py [-h] [--keywords KEYWORDS] [--prefix PREFIX] [--postfix POSTFIX] directory
#
# 必填 参数:
#   directory            文件夹地址
#
# 可选参数:
#   -h, --help          	显示帮助信息
#   --keywords 	要扫描的关键字信息，默认为 	tensorflow neo4j
#   --prefix PREFIX	要扫描的文件的前缀,	默认为	None
#   --postfix POSTFIX	要扫描的文件的后缀,	默认为	.py
#
# 示例：
# 输入：
# python scan_tool.py F:\share_to_linux\Deep_RL_Implementations --keywords tensor neo4j torch.nn --postfix .py
#
# 输出：
# find key word 'tensor' in file: F:\share_to_linux\Deep_RL_Implementations\agents\Base_Agent.py
# It's a Deep Learning or Knowledge Graph project